<template>
<!-- 检验模板维护 -->
  <p-card :bordered="false">

<!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form layout="inline" @keyup.enter.native="searchQuery">

        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="模板编码">
              <p-input placeholder="请输入模板编码" v-model="queryParam.templateCode"></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-item label="模板名称">
              <p-input placeholder="请输入模板名称" v-model="queryParam.templateName"></p-input>
            </p-form-item>
          </p-col>
            <p-col :xl="6" :lg="7" :md="8" :sm="24">
                <p-form-item label="二级工序编码">
                    <p-input placeholder="请输入二级工序编码" v-model="queryParam.processTwoCode"></p-input>
                </p-form-item>
            </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchQuery" icon="search">查询</p-button>
              <p-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</p-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <p-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </p-col>

        </p-row>

          <p-row :gutter="24" v-if="toggleSearchStatus">
              <p-col :xl="6" :lg="7" :md="8" :sm="24">
                  <p-form-item label="产品编码">
                      <p-input placeholder="产品编码" v-model="queryParam.mcode"></p-input>
                  </p-form-item>
              </p-col>



              <p-col :xl="6" :lg="7" :md="8" :sm="24">
                  <p-form-item label="模板类型">
                      <p-select v-model="queryParam.templateType" placeholder="请选择模板类型">
                          <p-select-option
                                  v-for="(item,index) in templateTypeList"
                                  :key="index"
                                  :value="parseInt(item.value)"
                          >{{item.title}}</p-select-option>
                      </p-select>
                  </p-form-item>
              </p-col>
          </p-row>

      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button @click="openAddBtn" type="primary" icon="plus">新增</p-button>
      <p-button @click="sendCheck" type="primary" >送审</p-button>

      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
          <p-button
            v-if=" item.optType=='js' && (item.groupTag == null || item.groupTag == '' )"
            :key=" 'cgbtn'+index "
            @click="cgButtonJsHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button>
          <p-button
            v-else-if=" item.optType=='action' && (item.groupTag == null || item.groupTag == '' )"
            :key=" 'cgbtn'+index "
            @click="cgButtonActionHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon"
          >{{ item.buttonName }}</p-button>
      </template>

        <!-- 高级查询区域 -->
        <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>

      <p-dropdown  v-for="(item,index) in groupTag" :key="index">
        <p-button >
          {{item.name}}
          <p-icon type="down" />
        </p-button>
          <p-menu slot="overlay"  >
            <template  v-for="(items,indexs) in item.data">
              <p-menu-item v-if=" items.optType=='js' " :key="indexs" @click="cgButtonJsHandler(items.buttonCode)">
                <p-icon :type="items.buttonIcon" />{{items.buttonName}}
              </p-menu-item>
              <p-menu-item v-else-if=" items.optType=='action' " :key="indexs" @click="cgButtonActionHandler(items.buttonCode)">
                <p-icon :type="items.buttonIcon" />{{items.buttonName}}
              </p-menu-item>
            </template>
          </p-menu>
      </p-dropdown>

      <p-dropdown v-if="selectedRowKeys.length > 0">
        <p-menu slot="overlay">
          <p-menu-item key="1" @click="batchDel"><p-icon type="delete"/>删除</p-menu-item>
        </p-menu>
        <p-button style="margin-left: 8px"> 批量操作 <p-icon type="down" /></p-button>
      </p-dropdown>
    </div>
    <!-- table区域-begin -->
    <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>

            <span style="float:right;">
              <a @click="handleExportXls('检验模板维护')"><p-icon type="download" />导出</a>
                 <p-divider type="vertical" />
              <p-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
                 <a><p-icon type="import" />导入</a>
              </p-upload>
              <p-divider type="vertical" />
              <a @click="loadData()"><p-icon type="sync" />刷新</a>
              <p-divider type="vertical" />
                <p-popover title="自定义列" trigger="click" placement="leftBottom"  :overlay-style="getWidth">
                <template slot="content">
                  <p-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                    <p-row>
                      <template v-for="(item,index) in defColumns">
                        <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                            <p-col :span="12"><p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox></p-col>
                        </template>
                      </template>
                    </p-row>
                  </p-checkbox-group>
                </template>
                <a><p-icon type="setting" />自定义列</a>
              </p-popover>
            </span>
        </div>


      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,}"
        :customRow="clickThenSelect"
        :rowClassName="setRowClassName"
        @change="handleTableChange">


          <template slot="templateCode" slot-scope="text,record">
              <a @click="openAllInfo(record)">{{text}}</a>
          </template>

          <template slot="status" slot-scope="text,record">
              <div v-if="!text" >/</div>
              <p-tag v-else-if="text==1" color="blue"><p-icon type="check-circle" />新增</p-tag>
              <p-tag v-else-if="text==2" color="#2db7f5"><p-icon type="clock-circle" />审核中</p-tag>
              <p-tag v-else-if="text==3" color="green"><p-icon type="check-circle" />生效</p-tag>
              <p-tag v-else-if="text==4" ><p-icon type="close-circle" />失效</p-tag>
              <p-tag v-else-if="text==5" color="red"><p-icon type="close-circle" />驳回</p-tag>
              <p-tag v-else-if="text==6" color="purple"><p-icon type="issues-close" />待送审</p-tag>
          </template>


          <template slot="productDetail" slot-scope="text,record">
              <p-icon type="plus" @click="openProductModal(record)"/>
          </template>
          <template slot="detailTemplate" slot-scope="text,record">
              <p-icon type="form" @click="detailTemplateBtn(record)"/>
          </template>


            <div slot="filterDropdown"
              slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
              style="padding: 8px">
              <p-input
                v-ant-ref="c => (searchInput = c)"
                :placeholder="`请输入 ${column.title}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block;"
                @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"/>
              <p-button
                type="primary"
                icon="search"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                确认
              </p-button>
              <p-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                取消
              </p-button>
            </div>
            <div
              slot="filterDropdownDate"
              slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
              style="padding: 8px">
              <p-form-item :label="` ${column.title}`">
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" class="query-group-cust" v-model="queryParam[`${column.dataIndex}_begin`]"></j-date>
                <span class="query-group-split-cust"></span>
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" class="query-group-cust" v-model="queryParam[`${column.dataIndex}_end`]"></j-date>
              </p-form-item>
              <p-button
                type="primary"
                icon="search"
                size="small"
                style="width: 90px; margin-right: 8px"
                @click="() => handleSearchDate(selectedKeys, confirm, column.dataIndex)">
                确认
              </p-button>
              <p-button size="small" style="width: 90px" @click="() => handleResetDate(clearFilters,`${column.dataIndex}_begin`,`${column.dataIndex}_end`)">
                取消
              </p-button>
            </div>
            <p-icon
              slot="filterIcon"
              slot-scope="filtered"
              type="search"
              :style="{ color: filtered ? '#108ee9' : undefined }"/>


            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无此图片</span>
              <img v-else :src="getImgView(text)" height="25px" alt="图片不存在" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
              <p-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="uploadFile(text)">
                下载
              </p-button>
            </template>






            <span slot="action" slot-scope="text, record">
              <a @click="openEditBtn(record)">编辑</a>

              <p-divider type="vertical" />
              <p-dropdown>
                <a class="ant-dropdown-link">更多 <p-icon type="down" /></a>
                <p-menu slot="overlay">
                  <p-menu-item>
                    <p-popconfirm title="确定删除吗?" @confirm="() => deleteBtn(record.id)">
                      <a>删除</a>
                    </p-popconfirm>
                  </p-menu-item>
                    <template v-if="cgButtonLinkList && cgButtonLinkList.length>0" v-for="(btnItem,btnIndex) in cgButtonLinkList">
                      <p-menu-item :key=" 'cgbtnLink'+btnIndex " v-if="showLinkButton(btnItem,record)">
                        <a href="javascript:void(0);" @click="cgButtonLinkHandler(record,btnItem.buttonCode,btnItem.optType)">
                          <p-icon v-if="btnItem.buttonIcon" :type="btnItem.buttonIcon" />
                          {{ btnItem.buttonName }}
                        </a>
                      </p-menu-item>
                    </template>
                </p-menu>
              </p-dropdown>
            </span>
      </p-table>
    </div>
      <div>
          <p-modal v-model="photoVisible" title="图片预览(非图片文件无法预览-需下载)" :footer="null" :width="1000">
              <img :src="photoUrl" class="myImg"/>
          </p-modal>
      </div>

    <mesQcInspectTemplateMaintain-modal ref="modalForm" :EnhanceJS="EnhanceJS"  @ok="modalFormOk"></mesQcInspectTemplateMaintain-modal>



      <p-modal v-model="pModalVisible" :title="pTitle" :width="900" @ok="pModalOk">
          <p-form-model
                  ref="ruleForm"
                  :model="form"
                  :rules="rules"
                  :label-col="labelCol" :wrapper-col="wrapperCol"
          >


              <p-form-model-item label="模板编码" prop="templateCode">
                  <p-input v-model="form.templateCode"  readOnly/>
              </p-form-model-item>

              <p-form-model-item label="模板名称" prop="templateName">
                  <p-input v-model="form.templateName"/>
              </p-form-model-item>

              <p-form-model-item label="模板类型" prop="templateType">
                  <p-select v-model="form.templateType" placeholder="请选择模板类型" @change="initProcessTwoList">
                      <p-select-option
                              v-for="(item,index) in templateTypeList"
                              :key="index"
                              :value="parseInt(item.value)"
                      >{{item.title}}</p-select-option>
                  </p-select>
              </p-form-model-item>


              <p-form-model-item label="二级工序" prop="processTwoId" v-if="form.templateType==1||form.templateType==2">
                  <p-select v-model="form.processTwoId" placeholder="请选择二级工序" @change="processTwoSelectChange" showSearch>
                      <p-select-option
                              v-for="(item,index) in processTwoList"
                              :key="index"
                              :value="item.id+'-'+item.processmname"
                      >{{item.processmname}}</p-select-option>
                  </p-select>
              </p-form-model-item>



             <p-form-model-item label="是否供应商模板" prop="isCustTemplate">
                  <p-select v-model="form.isCustTemplate" :disabled="form.templateType!=5">
                      <p-select-option :value="1">是</p-select-option>
                      <p-select-option :value="2">否</p-select-option>
                  </p-select>
              </p-form-model-item>


              <p-form-model-item label="备注" prop="remark">
                  <p-input v-model="form.remark"/>
              </p-form-model-item>


          </p-form-model>

      </p-modal>


      <p-modal v-model="pdSmallModalVisible" :title="pdSmallModalTitle" :maskClosable="false" :width="900"   :footer="null">
          <p-form-model
                  ref="ruleForm"
                  :model="pdForm"
                  :label-col="labelCol" :wrapper-col="wrapperCol"
          >
              <p-form-model-item label="产品/物料编码" prop="mid">
                  <p-select
                          show-search
                          :value="pdForm.mcode"
                          placeholder="可输入物料编码搜索"
                          :default-active-first-option="false"
                          :show-arrow="false"
                          :filter-option="false"
                          :not-found-content="null"
                          @search="productSearch"

                  >
                      <div slot="dropdownRender" >
                          <p-table
                                  :columns="pruductSmallColumns"
                                  :data-source="productList"
                                  :pagination="false"
                                  :customRow="selectPruductSmall"
                                  bordered
                                  :scroll="{ x: 500, y: 300 }"
                          >
                          </p-table>
                      </div>
                      <!--<p-select-option
                              v-for="(item,index) in productList"
                              :key="index"
                              :value="item.id"
                      >{{item.mcode}}</p-select-option>-->

                  </p-select>
              </p-form-model-item>
              <p-form-model-item label="产品/物料名称" prop="mname">
                  <p-input v-model="pdForm.mname"/>
              </p-form-model-item>

              <p-form-model-item label="封样图片" prop="mname">
                  <j-upload v-model="pdForm.fileUrl" :trigger-change="true" :ismultiSelect="false" @change="fileChange"></j-upload>
              </p-form-model-item>



          </p-form-model>

          <p-row style="text-align: center">
              <p-button type="primary" style="margin-right: 8px" @click="saveProductDetail" >保存</p-button>
              <p-button @click="closeProductModal">取消</p-button>
          </p-row>


      </p-modal>






      <p-modal v-model="productModalVisible" title="产品/物料明细"  :width="1300"   :footer="null">
          <p-row :gutter="24"  >
              <p-col :span="7" >
                  <p-button type="primary" style="margin-right: 5px" @click="openAddPdBtn">新增</p-button>

                  <p-popconfirm  v-if="productSelectRowKeys.length>0" title="确定删除吗?" @confirm="() => deleteProductRows()">
                      <p-button  type="danger">删除</p-button>
                  </p-popconfirm>


              </p-col>
              <p-col :span="7" >
                  <p-input v-model="productSearchStr" placeholder="产品/物料编码/名称" @change="queryProductDetailList"/>
              </p-col>
              <p-col :span="2" >
              </p-col>

          </p-row>

          <p-table

                  :columns="productTableColumns"
                  :data-source="productTableData"
                  class="components-table-demo-nested"
                  bordered
                  style="margin-top:10px;"
                  :rowSelection="{selectedRowKeys: productSelectRowKeys, onChange: productOnSelectChange,}"
          >


              <template slot="fileSlot2" slot-scope="text">
                  <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
                  <div v-else>
                      <p-button
                              type="primary"
                              style="margin-right: 16px;"
                              @click="openPhotoBtn(text)"
                      > <p-icon type="eye" />预览</p-button>
                  </div>
              </template>

              <template slot="edit" slot-scope="text,record">
                  <a @click="openProductEditBtn(record)">编辑</a>
              </template>

          </p-table>


      </p-modal>



      <p-modal v-model="templateModalVisible" :title="templateTitle" :maskClosable="false" :width="1400" @ok="templateSaveBtn" okText="保存" cancelText="关闭" >

          <p-row :gutter="24"  v-if="templateTableData.length==0">
              <p-col :span="10" >
                  <p-form-model :model="templateForm" :label-col="labelCol" :wrapper-col="wrapperCol">



                      <p-form-model-item label="参考产品/物料编码" prop="mid">
                          <p-select
                                  show-search
                                  :value="templateForm.mcode"
                                  placeholder="可输入物料编码搜索"
                                  :default-active-first-option="false"
                                  :dropdownMatchSelectWidth="false"
                                  :show-arrow="false"
                                  :filter-option="false"
                                  :not-found-content="null"
                                  @search="productSearch"
                          >
                              <div slot="dropdownRender" >
                                  <p-table
                                          :columns="pruductSmallColumns"
                                          :data-source="productList"
                                          :pagination="false"
                                          :customRow="productChange2"
                                          bordered
                                          :scroll="{ x: 500, y: 300 }"
                                  >
                                  </p-table>
                              </div>

                          </p-select>
                      </p-form-model-item>
                  </p-form-model>


              </p-col>

              <p-col :span="10" >
                  <p-form-model :model="templateForm" :label-col="labelCol" :wrapper-col="wrapperCol">
                      <p-form-model-item label="参考产品/物料名称 ">
                          <p-input v-model="templateForm.mname" disabled/>
                      </p-form-model-item>
                  </p-form-model>
              </p-col>




              <p-col :span="4" >
                  <p-button type="primary" @click="queryOtherData">确定</p-button>
              </p-col>

          </p-row>


          <p-row :gutter="24"  >
              <p-col :span="18" >
                  <p-button  type="primary"  style="margin-right: 5px" @click="openTemplateAddBtn">新增</p-button>

                  <p-popconfirm v-if="templateSelectRowKeys.length>0" title="确定删除吗?" @confirm="() => deleteSelectTemplate()">
                      <p-button  type="danger">删除</p-button>
                  </p-popconfirm>

              </p-col>
              <p-col :span="3" >

              </p-col>
              <p-col :span="3" >

              </p-col>
          </p-row>

          <p-table

                  :columns="templateColType==1?templateTableColumns:templateTableColumns1"
                  :data-source="templateTableData"
                  class="components-table-demo-nested"
                  bordered
                  style="margin-top:10px;"
                  :rowSelection="{selectedRowKeys: templateSelectRowKeys, onChange: templateOnSelectChange,}"
          >

              <tamplate  slot="workstationId" slot-scope="text,record">
                  <p-select  v-model="record.workstationId" showSearch style="width:200px">
                      <p-select-option
                              v-for="(item,index) in workStationList"
                              :key="index"
                              :value="item.id+'-'+item.processmname"
                      >{{item.processmname}}</p-select-option>
                  </p-select>
              </tamplate>

              <tamplate  slot="standardValue" slot-scope="text,record">
                  <p-select v-if="record.valueType==2" v-model="record.standardValue">
                      <p-select-option value="PASS">PASS</p-select-option>
                      <p-select-option value="NG">NG</p-select-option>
                  </p-select>

                  <p-input v-if="record.valueType==1" type="number" v-model="record.standardValue" style="width:100px"/>
              </tamplate>

              <tamplate  slot="standardUnit" slot-scope="text,record">
                  <p-select  v-model="record.standardUnit">
                      <p-select-option
                              v-for="(item,index) in standardUnitList"
                              :key="index"
                              :value="parseInt(item.value)"
                      >{{item.title}}</p-select-option>
                  </p-select>
              </tamplate>

              <tamplate  slot="upperValue" slot-scope="text,record">
                  <p-input v-if="record.valueType==1" type="number" v-model="record.upperValue" style="width:100px"/>
              </tamplate>

              <tamplate  slot="downValue" slot-scope="text,record">
                  <p-input v-if="record.valueType==1" type="number" v-model="record.downValue" style="width:100px"/>
              </tamplate>

              <tamplate  slot="param" slot-scope="text,record">
                  <p-input   v-model="record.param" style="width:100px"/>
              </tamplate>
              <tamplate  slot="flawLevel" slot-scope="text,record">
                  <p-select v-model="record.flawLevel">
                      <p-select-option
                              v-for="(item,index) in errorLevelList"
                              :key="index"
                              :value="parseInt(item.value)"
                      >{{item.title}}</p-select-option>
                  </p-select>
              </tamplate>
              <tamplate  slot="sort" slot-scope="text,record">
                  <div style="width:120px">
                      <p-button  icon="arrow-up" style="margin-right: 6px" v-if="record.key!=1" @click="arrowUp(record)"/>
                      <p-button  icon="arrow-down" style="margin-right: 6px" v-if="record.key!=templateTableData.length" @click="arrowDown(record)"/>
                      <p-dropdown v-if="templateTableData.length!=1">
                          <p-menu slot="overlay" @click="handleMenuClick" >
                              <p-menu-item key="1" v-if="record.key!=1" @click="indexToFirst(record)"> 移至最前 </p-menu-item>
                              <p-menu-item key="2" v-if="record.key!=templateTableData.length" @click="indexToLast(record)"> 移至最后 </p-menu-item>
                          </p-menu>
                          <p-button icon="more">  </p-button>
                      </p-dropdown>
                  </div>
              </tamplate>

          </p-table>

      </p-modal>

      <p-modal v-model="checkProjectVisible" title="详细模板添加检验项目" :maskClosable="false" :width="1000" @ok="checkProjectAddBtn" okText="保存" cancelText="关闭">
          <p-row :gutter="24"  >

              <p-col :span="7" >
                          <p-input v-model="cpSearchParam.checkProjectSearch" placeholder="检验项目编码/名称" @change="checkProjectSearchChange"/>
              </p-col>

              <p-col :span="8" >
                  项目类型:
                  <p-select allowClear style="width:230px" v-model="cpSearchParam.projectTypeId" placeholder="请选择项目类型" @change="projectTypeIdChange">
                      <p-select-option
                              v-for="(item,index) in projectTypeList"
                              :key="index"
                              :value="parseInt(item.value)"
                      >{{item.title}}</p-select-option>
                  </p-select>
              </p-col>

              <p-col :span="8" >
                  项目分类 :
                  <p-select showSearch allowClear style="width:230px"  v-model="cpSearchParam.projectClassifyId" @change="projectClassifyIdChange" placeholder="请选择项目分类" showSearch v-if="cpSearchParam.projectTypeId==1">
                      <p-select-option
                              v-for="(item,index) in projectClassifyList"
                              :key="index"
                              :value="item.id+'-'+item.mtypename"
                      >{{item.mtypename}}</p-select-option>
                  </p-select>
                  <p-select showSearch allowClear style="width:230px" v-model="cpSearchParam.projectClassifyId" @change="projectClassifyIdChange" placeholder="请选择项目分类" showSearch v-if="cpSearchParam.projectTypeId==2">
                      <p-select-option
                              v-for="(item,index) in projectClassifyList"
                              :key="index"
                              :value="item.projectClassifyId+'-'+item.projectClassify"
                      >{{item.projectClassify}}</p-select-option>
                  </p-select>

                  <p-select showSearch allowClear style="width:230px" v-model="cpSearchParam.projectClassifyId" @change="projectClassifyIdChange" placeholder="请选择项目分类" showSearch v-if="cpSearchParam.projectTypeId!=2&&cpSearchParam.projectTypeId!=1">
                      <p-select-option
                              v-for="(item,index) in projectClassifyList"
                              :key="index"
                              :value="parseInt(item.value)+'-'+item.title"
                      >{{item.title}}</p-select-option>
                  </p-select>
              </p-col>

          </p-row>

          <p-table

                  :columns="checkProjectTableColumns"
                  :data-source="checkProjectTableData"
                  class="components-table-demo-nested"
                  borderedMesQcInspectIndexLibraryList
                  style="margin-top:10px;"
                  :rowSelection="{selectedRowKeys: checkProjectSelectRowKeys, onChange: checkProjectOnSelectChange,}"
          >


          </p-table>

      </p-modal>


      <p-drawer
              title="详情"
              placement="right"
              :closable="false"
              :width="900"
              :visible="detailVisible"
              @close="closeDetailBtn"
      >
          <p-divider orientation="left">
              主信息
          </p-divider>

          <p-descriptions  bordered size="small">
              <p-descriptions-item label="模板编码">
                  {{de.templateCode}}
              </p-descriptions-item>
              <p-descriptions-item label="模板名称">
                  {{de.templateName}}
              </p-descriptions-item>
              <p-descriptions-item label="模板类型">
                  {{templateTypeMap[de.templateType]?templateTypeMap[de.templateType].title:''}}
              </p-descriptions-item>
              <p-descriptions-item label="二级工序编码">
                  {{de.processTwoCode}}
              </p-descriptions-item>
              <p-descriptions-item label="二级工序名称" :span="2">
                  {{de.processTwoName}}
              </p-descriptions-item>
              <p-descriptions-item label="状态">
                  <div v-if="!de.status" >/</div>
                  <p-tag v-else-if="de.status==1" color="blue"><p-icon type="check-circle" />新增</p-tag>
                  <p-tag v-else-if="de.status==2" color="#2db7f5"><p-icon type="clock-circle" />审核中</p-tag>
                  <p-tag v-else-if="de.status==3" color="green"><p-icon type="check-circle" />生效</p-tag>
                  <p-tag v-else-if="de.status==4" ><p-icon type="close-circle" />失效</p-tag>
                  <p-tag v-else-if="de.status==5" color="red"><p-icon type="close-circle" />驳回</p-tag>
                  <p-tag v-else-if="de.status==6" color="purple"><p-icon type="issues-close" />待送审</p-tag>
              </p-descriptions-item>
              <p-descriptions-item label="是否供应商模板" :span="2">
                  <div v-if="!de.isCustTemplate" ></div>
                  <p-tag v-else-if="de.isCustTemplate==1" color="green"> <div style="color:#00FF00">是</div></p-tag>
                  <p-tag v-else-if="de.isCustTemplate==2" color="red"> <div style="color:red">否</div></p-tag>
              </p-descriptions-item>
              <p-descriptions-item label="创建者" :span="2">
                  {{de.createBy}}
              </p-descriptions-item>
              <p-descriptions-item label="创建日期">
                  {{de.createTime?dayjs(de.createTime).format('YYYY-MM-DD'):''}}
              </p-descriptions-item>

              <p-descriptions-item label="修改者" :span="2">
                  {{de.updateBy}}
              </p-descriptions-item>
              <p-descriptions-item label="更新日期">
                  {{de.updateTime?dayjs(de.updateTime).format('YYYY-MM-DD'):''}}
              </p-descriptions-item>

              <p-descriptions-item label="备注" :span="3">
                  {{de.remark}}
              </p-descriptions-item>
          </p-descriptions>

          <p-divider orientation="left">
              其他信息
          </p-divider>

          <p-collapse v-model="activeKey">
              <p-collapse-panel key="1" header="产品/物料明细">
                  <p-table

                          :columns="productTableColumns1"
                          :data-source="de.mesQcQualityFileProductDetailList"
                          class="components-table-demo-nested"
                          bordered
                          style="margin-top:10px;"
                  >


                      <template slot="fileSlot2" slot-scope="text">
                          <span v-if="!text" style="font-size: 12px;font-style: italic;">无此文件</span>
                          <div v-else>
                              <p-button
                                      type="primary"
                                      style="margin-right: 16px;"
                                      @click="openPhotoBtn(text)"
                              > <p-icon type="eye" />预览</p-button>
                          </div>
                      </template>

                      <template slot="edit" slot-scope="text,record">
                          <a @click="openProductEditBtn(record)">编辑</a>
                      </template>

                  </p-table>
              </p-collapse-panel>
              <p-collapse-panel key="2" header="模板明细">
                  <p-table

                          :columns="(de.templateType!=1&&de.templateType!=2)?templateTableColumns1T:templateTableColumnsT"
                          :data-source="de.mesQcDetailTemplateMaintainList"
                          class="components-table-demo-nested"
                          bordered
                          style="margin-top:10px;"
                  >

                  </p-table>
              </p-collapse-panel>

              <p-collapse-panel key="3" header="流程记录">
                  <p-table ref="table"
                           size="middle"
                           bordered :columns="recordColumns" rowKey="id" :dataSource="de.approvalList">

                  </p-table>

              </p-collapse-panel>
          </p-collapse>

      </p-drawer>


     <!-- 弹出窗 -->
     <Fx-compontens-modal @ok="modalFormOk"  ref="modalCompon" :getList="queryInfo" :title="title" :dictOptions="dictOptions"></Fx-compontens-modal>
  </p-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {api} from '@/api/manage'
  import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
  import { filterObj } from '@/utils/util'
  import MesQcInspectTemplateMaintainModal from './modules/MesQcInspectTemplateMaintainModal'
  import Vue from 'vue'
  import MesQcDetailTemplateMaintainList from './MesQcDetailTemplateMaintainList'
  import MesQcQualityFileList from './MesQcQualityFileList'
  import {initDictOptions, filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import ButtonExpHandler from '@/components/jeecgbiz/modules/ButtonExpHandler'
  import { postAction,getAction,deleteAction,putAction } from '@/api/manage'
  import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal"
  import TesttableList from "../mesInfo/TesttableList";
  import  dayjs   from 'dayjs';
  import JUpload from '@/components/jeecg/JUpload'
  //高级查询modal需要参数
    const superQueryFieldList=[
            {
                value:'templateCode',
                text: '模板编码',
                type: 'String'
            },
            {
                value:'templateName',
                text: '模板名称',
                type: 'String'
            },
            {
                value:'templateType',
                text: '模板类型',
                type: 'select',
                dictCode: 'mes_template_type'
            },
            {
                value:'processTwoCode',
                text: '二级工序编码',
                type: 'String'
            },
            {
                value:'processTwoName',
                text: '二级工序名称',
                type: 'String'
            },
            {
                value:'isCustTemplate',
                text: '是否供应商模板',
                type: 'select',
                dictCode: 'ba_yn'
            },
            {
                value:'status',
                text: '状态',
                type: 'select',
                dictCode: 'mes_audit_status'
            },
            {
                value:'inspectProjectCode',
                text: '检验项目编码',
                type: 'String',
            },
        {
            value:'inspectProject',
            text: '检验项目名称',
            type: 'String',
        },
        {
            value:'mcode',
            text: '产品编码',
            type: 'String',
        },
        {
            value:'mname',
            text: '产品名称',
            type: 'String',
        },
        {
            value:'createTime',
            text: '创建日期',
            type: 'Date',
        },
        {
            value:'updateTime',
            text: '更新日期',
            type: 'Date',
        },
        {
            value:'createBy',
            text: '创建人',
            type: 'String',
        },
        {
            value:'updateBy',
            text: '更新人',
            type: 'String',
        },
    ]

  export default {
    name: "MesQcInspectTemplateMaintainList",
    mixins:[JeecgListMixin],
    components: {
        TesttableList,
      JSuperQuery,
      MesQcDetailTemplateMaintainList,
      MesQcQualityFileList,
      FxCompontensModal,
      MesQcInspectTemplateMaintainModal,
        JUpload
    },
    data () {
      return {
        fieldList:superQueryFieldList,
        superQueryFlag:false,
        superQueryParams: '',
        description: '检验模板维护管理页面',
        EnhanceJS:'',
        cgButtonLinkList:[],
        cgButtonList:[],
          photoUrl:'',
          photoVisible:false,
          templateCode:'',
          templateTypeList:[],
          templateTypeMap:[],
          methodList:[],
          methodMap: [],
          processTwoList:[],
          processTwoMap:[],

          templateUnitList:[],
          templateUnitMap:[],

          detailVisible:false,

          de:{},

          activeKey:['1'],

          pModalVisible:false,
          editP:{},
          pTitle:'',

          productModalVisible:false,
          productSearchStr:'',

          templateModalVisible:false,
          templateTitle:'',

          templateForm:{
            mid:'',
            mcode:'',
              mname:'',
          },

          templateSelectRowKeys:[],
          templateSelectRows:[],
          errLevelList:[],
          errLevelMap:[],

          checkProjectSelectRowKeys:[],
          checkProjectSelectRows:[],

          productSelectRowKeys:[],
          productSelectRows:[],

          productEditP:{},

          labelCol: { span: 6 },
          wrapperCol: { span: 16 },
          currentState:1,

          isGetEdit:false,

          form: {
              templateCode:'',
              templateName:'',
              templateType:'',
              processTwoId:'',
              isCustTemplate:'',
              remark:'',
          },


          recordColumns:[
              {
                  title: "序号",
                  dataIndex: "",
                  key: "rowIndex",
                  width: 60,
                  align: "center",
                  customRender: function (t, r, index) {
                      return parseInt(index) + 1;
                  },
              },
              {
                  title: "创建时间",
                  align: "center",
                  dataIndex: "startTime",
              },
              {
                  title: "处理时间",
                  align: "center",
                  dataIndex: "endTime",
              },
              {
                  title: "节点名称",
                  align: "center",
                  dataIndex: "activityName",
              },
              {
                  title: "执行人",
                  align: "center",
                  dataIndex: "assigneeName",
              },
              {
                  title: "操作",
                  align: "center",
                  dataIndex: "operator",
              },
              {
                  title: "处理意见",
                  align: "center",
                  dataIndex: "comment",
              },
          ],

          rules: {
              templateName: [{ required: true, message: '请输入模板名称', trigger: 'change' }],
              templateType: [{ required: true, message: '请选择模板类型', trigger: 'change' }],
          },

          templateTableData:[],
          indexModalVisible:false,

          sortFlag:false,

          pruductSmallColumns:[
              {
                  title: '产品/物料编码',
                  align: 'center',
                  dataIndex: 'mcode',
              },
              {
                  title: '产品/物料名称',
                  align: 'center',
                  dataIndex: 'mname',
              },
          ],

          templateColType:1,

          currentBasicId:0,


          productTableColumns:[
              {
                  title: '产品/物料编码',
                  align: 'center',
                  dataIndex: 'mcode',
              },
              {
                  title: '产品/物料名称',
                  align: 'center',
                  dataIndex: 'mname',
              },

              {
                  title: '封样图片',
                  align: 'center',
                  dataIndex: 'fileUrl',
                  scopedSlots: { customRender: "fileSlot2" },
              },
              {
                  title: '创建者',
                  align: 'center',
                  dataIndex: 'createBy',
              },
              {
                  title: '创建日期',
                  align: 'center',
                  dataIndex: 'createTime',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                           return dayjs(text).format('YYYY-MM-DD')
                      }
                  }
              },
              {
                  title: '修改者',
                  align: 'center',
                  dataIndex: 'updateBy',
              },
              {
                  title: '修改日期',
                  align: 'center',
                  dataIndex: 'updateTime',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return dayjs(text).format('YYYY-MM-DD')
                      }
                  }
              },
              {
                  title: '编辑',
                  align: 'center',
                  dataIndex: 'id',
                  scopedSlots: { customRender: 'edit' },
              },
          ],

          productTableColumns1:[
              {
                  title: '产品/物料编码',
                  align: 'center',
                  dataIndex: 'mcode',
              },
              {
                  title: '产品/物料名称',
                  align: 'center',
                  dataIndex: 'mname',
              },

              {
                  title: '封样图片',
                  align: 'center',
                  dataIndex: 'fileUrl',
                  scopedSlots: { customRender: "fileSlot2" },
              },
              {
                  title: '创建者',
                  align: 'center',
                  dataIndex: 'createBy',
              },
              {
                  title: '创建日期',
                  align: 'center',
                  dataIndex: 'createTime',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return dayjs(text).format('YYYY-MM-DD')
                      }
                  }
              },
              {
                  title: '修改者',
                  align: 'center',
                  dataIndex: 'updateBy',
              },
              {
                  title: '修改日期',
                  align: 'center',
                  dataIndex: 'updateTime',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return dayjs(text).format('YYYY-MM-DD')
                      }
                  }
              },

          ],
          productTableData:[
          ],

          templateTableColumns:[
              {
                  title: '工站',
                  align: 'center',
                  dataIndex: 'workstationId',
                  scopedSlots: { customRender: 'workstationId' },
              },
              {
                  title: '检验项目',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectProjectName',
              },
              {
                  title: '检验标准',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectStandard',

              },
              {
                  title: '值类型',
                  align: 'center',
                  dataIndex: 'valueType',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return text==1?'计量型':'计数型';
                      }

                  }
              },
              {
                  title: '检验手段',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectMethod',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return this.inspectMethodMap[text].title
                      }

                  }
              },
              {
                  title: '标准值',
                  align: 'center',
                  dataIndex: 'standardValue',
                  scopedSlots: { customRender: 'standardValue' },
              },
              {
                  title: '单位',
                  align: 'center',
                  dataIndex: 'standardUnit',
                  scopedSlots: { customRender: 'standardUnit' },
              },
              {
                  title: '上限值',
                  align: 'center',
                  dataIndex: 'upperValue',
                  scopedSlots: { customRender: 'upperValue' },
              },
              {
                  title: '下限值',
                  align: 'center',
                  dataIndex: 'downValue',
                  scopedSlots: { customRender: 'downValue' },
              },
              {
                  title: '参数',
                  align: 'center',
                  dataIndex: 'param',
                  scopedSlots: { customRender: 'param' },
              },
              {
                  title: '缺陷等级',
                  align: 'center',
                  dataIndex: 'flawLevel',
                  scopedSlots: { customRender: 'flawLevel' },
              },
              {
                  title: '排序',
                  align: 'center',
                  dataIndex: 'sort',
                  scopedSlots: { customRender: 'sort' },
              },
          ],

          templateTableColumnsT:[
              {
                  title: '工站',
                  align: 'center',
                  dataIndex: 'workstationname',
              },
              {
                  title: '检验项目',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectProjectName',
              },
              {
                  title: '检验标准',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectStandard',

              },
              {
                  title: '值类型',
                  align: 'center',
                  dataIndex: 'valueType',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return text==1?'计量型':'计数型';
                      }

                  }
              },
              {
                  title: '检验手段',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectMethod',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return this.inspectMethodMap[text].title
                      }

                  }
              },
              {
                  title: '标准值',
                  align: 'center',
                  dataIndex: 'standardValue',
              },
              {
                  title: '单位',
                  align: 'center',
                  dataIndex: 'standardUnit',
                  customRender:(text)=>{
                          return this.standardUnitMap[text]?this.standardUnitMap[text].title:''
                  }
              },
              {
                  title: '上限值',
                  align: 'center',
                  dataIndex: 'upperValue',
              },
              {
                  title: '下限值',
                  align: 'center',
                  dataIndex: 'downValue',
              },
              {
                  title: '参数',
                  align: 'center',
                  dataIndex: 'param',
              },
              {
                  title: '缺陷等级',
                  align: 'center',
                  dataIndex: 'flawLevel',
                  customRender:(text)=>{
                      if(!text){
                          return ''
                      }else{
                          return  this.errLevelMap[text]?this.errLevelMap[text].title:'';
                      }
                  },
              },


          ],
          templateTableColumns1T:[
              {
                  title: '检验项目',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectProjectName',

              },
              {
                  title: '检验标准',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectStandard',
              },
              {
                  title: '值类型',
                  align: 'center',
                  dataIndex: 'valueType',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return text==1?'计量型':'计数型';
                      }
                  }
              },
              {
                  title: '检验手段',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectMethod',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return this.inspectMethodMap[text].title
                      }

                  }
              },
              {
                  title: '标准值',
                  align: 'center',
                  dataIndex: 'standardValue',
                  scopedSlots: { customRender: 'standardValue' },
              },
/*              {
                  title: '单位',
                  align: 'center',
                  dataIndex: 'standardUnit',
                  scopedSlots: { customRender: 'standardUnit' },
              },*/
              {
                  title: '单位',
                  align: 'center',
                  dataIndex: 'standardUnit',
                  customRender:(text)=>{
                      if(!text){
                          return ''
                      }else{
                          return  this.templateUnitMap[text]?this.templateUnitMap[text].title:'';
                      }
                  },
              },
              {
                  title: '上限值',
                  align: 'center',
                  dataIndex: 'upperValue',
                  scopedSlots: { customRender: 'upperValue' },
              },
              {
                  title: '下限值',
                  align: 'center',
                  dataIndex: 'downValue',
                  scopedSlots: { customRender: 'downValue' },
              },
              {
                  title: '参数',
                  align: 'center',
                  dataIndex: 'param',
                  scopedSlots: { customRender: 'param' },
              },
              {
                  title: '缺陷等级',
                  align: 'center',
                  dataIndex: 'flawLevel',
                  customRender:(text)=>{
                      if(!text){
                          return ''
                      }else{
                          return  this.errorLevelMap[text]?this.errorLevelMap[text].title:'';
                      }
                  },
              },

          ],
          templateTableColumns1:[
              {
                  title: '检验项目',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectProjectName',

              },
              {
                  title: '检验标准',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectStandard',
              },
              {
                  title: '值类型',
                  align: 'center',
                  dataIndex: 'valueType',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return text==1?'计量型':'计数型';
                      }
                  }
              },
              {
                  title: '检验手段',
                  align: 'center',
                  dataIndex: 'mesQcInspectIndexLibrary.inspectMethod',
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return this.inspectMethodMap[text].title
                      }

                  }
              },
              {
                  title: '标准值',
                  align: 'center',
                  dataIndex: 'standardValue',
                  scopedSlots: { customRender: 'standardValue' },
              },
              {
                  title: '单位',
                  align: 'center',
                  dataIndex: 'standardUnit',
                  scopedSlots: { customRender: 'standardUnit' },
              },
              {
                  title: '上限值',
                  align: 'center',
                  dataIndex: 'upperValue',
                  scopedSlots: { customRender: 'upperValue' },
              },
              {
                  title: '下限值',
                  align: 'center',
                  dataIndex: 'downValue',
                  scopedSlots: { customRender: 'downValue' },
              },
              {
                  title: '参数',
                  align: 'center',
                  dataIndex: 'param',
                  scopedSlots: { customRender: 'param' },
              },
              {
                  title: '缺陷等级',
                  align: 'center',
                  dataIndex: 'flawLevel',
                  scopedSlots: { customRender: 'flawLevel' },
              },
              {
                  title: '排序',
                  align: 'center',
                  dataIndex: 'sort',
                  scopedSlots: { customRender: 'sort' },
              },
          ],
          pdSmallModalVisible:false,
          pdSmallModalTitle:'',
          pdCurrentState:1,

          errorLevelList:[],
          errorLevelMap:[],

          workStationList:[],
          workStationMap:[],

          pdForm:{
              mid:'',
              mcode:'',
              mname:'',
          },

          checkProjectVisible:false,
          checkProjectSearch:'',
          cpSearchParam:{
              checkProjectSearch:'',
              projectClassifyId:'',
              projectTypeId:'',
          },
          checkProjectTableData:[],
          checkProjectTableColumns:[
              {
                  title: "序号",
                  dataIndex: "",
                  key: "rowIndex",
                  width: 60,
                  align: "center",
                  customRender: function (t, r, index) {
                      return parseInt(index) + 1;
                  },
              },
              {
                  title: "检验项目编码",
                  align: "center",
                  dataIndex: "inspectProjectCode",

              },
              {
                  title: "检验项目名称",
                  align: "center",
                  dataIndex: "inspectProjectName",
              },
              {
                  title: "项目类型",
                  align: "center",
                  dataIndex: "projectType",
              },
              {
                  title: "项目分类",
                  align: "center",
                  dataIndex: "projectClassify",
              },

              {
                  title: "检验标准",
                  align: "center",
                  dataIndex: "inspectStandard",
              },
              {
                  title: "检验值类型",
                  align: "center",
                  dataIndex: "inspectValueType",
                  customRender:(text)=>{
                      if(!text){
                          return '';
                      }else{
                          return text==1?'计量型':'计数型';
                      }
                  }
              },
              {
                  title: '检验手段',
                  align: 'center',
                  dataIndex: 'inspectMethod',
                  customRender:(text)=>{
                      if(!text){
                          return "";
                      }else{
                          if(this.inspectMethodMap[text]){
                              return this.inspectMethodMap[text].title;
                          }
                          return  "";
                      }
                  }
              },

          ],
          productList:[],
          productMap:[],

          rowId:0,



          projectTypeList:[],
          projectTypeMap:[],

          standardUnitList:[],
          standardUnitMap:[],

          projectClassifyList:[],
          projectClassifyMap:[],
          projectClassifyList1:[],
          projectClassifyMap1:[],
          projectClassifyList2:[],
          projectClassifyMap2:[],
          projectClassifyList3:[],
          projectClassifyMap3:[],

        title:'',//存表名
        groupTag:[],
        queryInfo: [],
        code: '',
        // 表头
        columns: [],
         //列设置
         settingColumns:[],
         //列定义
         defColumns: [
             {
                 title: "序号",
                 dataIndex: "",
                 key: "rowIndex",
                 width: 50,
                 align: "center",
                 customRender: function (t, r, index) {
                     return parseInt(index) + 1;
                 },

             },
             {
                 title: '产品/物料明细',
                 align: 'center',
                 width: 65,
                 dataIndex: 'id',
                 scopedSlots: { customRender: 'productDetail' },
             },
         {
             title: '详细模板',
             align: 'center',
             width: 65,
             dataIndex: 'id',
             scopedSlots: { customRender: 'detailTemplate' },
         },
          {
            title: '模板编码',
            align: 'center',
            dataIndex: 'templateCode',
              width:120,
              scopedSlots: { customRender: "templateCode" },
          },
          {
            title: '模板名称',
            align: 'center',
              width:220,
            dataIndex: 'templateName',
          },
          {
            title: '模板类型',
            align: 'center',
            dataIndex: 'templateType',
            customRender:(text)=>{
              if(!text){
                return ''
              }else{
                return filterMultiDictText(this.dictOptions['templateType'], text+"")
              }
            },
          },
          {
            title: '二级工序编码',
            align: 'center',
            dataIndex: 'processTwoCode',

          },
          {
            title: '二级工序名称',
            align: 'center',
            dataIndex: 'processTwoName',
          },
          {
            title: '是否供应商模板',
            align: 'center',
            dataIndex: 'isCustTemplate',
              customRender: (text) => {
                  if (!text) {
                      return ''
                  } else {
                      if(text==1){
                          return <p-tag color="green"> <div style="color:#00FF00">是</div></p-tag>;
                      }else {
                          return <p-tag color="red"> <div style="color:red">否</div></p-tag>;
                      }
                  }
              },

          },


             {
                 title: "创建人",
                 align: "center",
                 dataIndex: "createBy",
             },
             {
                 title: "创建日期",
                 align: "center",
                 dataIndex: "createTime",
                 customRender: function (text) {
                     return !text ? "" : text.length > 10 ? text.substr(0, 10) : text;
                 },
             },
             {
                 title: "更新人",
                 align: "center",
                 dataIndex: "updateBy",
             },
             {
                 title: "更新日期",
                 align: "center",
                 dataIndex: "updateTime",
                 customRender: function (text) {
                     return !text ? "" : text.length > 10 ? text.substr(0, 10) : text;
                 },
             },
             {
                 title: "备注",
                 align: "center",
                 width:220,
                 dataIndex: "remark",
             },
             {
                 title: '状态',
                 align: 'center',
                 dataIndex: 'status',
                 scopedSlots: { customRender: 'status' },

             },

          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: '/mes-quality/mesQcInspectTemplateMaintain/list',
          delete: '/mes-quality/mesQcInspectTemplateMaintain/delete',
          deleteBatch: '/mes-quality/mesQcInspectTemplateMaintain/deleteBatch',
          exportXlsUrl: '/mes-quality/mesQcInspectTemplateMaintain/exportXls',
          importExcelUrl: '/mes-quality/mesQcInspectTemplateMaintain/importExcel',
          getColumns: '/mes-quality/online/cgform/api/getColumns/',
          buttonAction: '/mes-quality/online/cgform/api/doButton',
        },
        dictOptions:{
         templateType:[],
         isCustTemplate:[],
         status:[],
            inspectMethodList:[],
            inspectMethodMap:[],
        },
        /* 分页参数 */
        ipagination:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '50'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        selectedMainId:''

      }
    },
    computed: {
      importExcelUrl: function(){
        return `${api.test}${this.url.importExcelUrl}`;
      },
      getWidth:function(){
        if(this.defColumns.length > 14){
          return {width : '500px'}
        }
      },
      newSelectedMainId:function(){
        if(typeof(this.selectedMainId) == 'number'){
          return this.selectedMainId.toString()
        }else{
          return this.selectedMainId
        }
      },
			tableScroll:function(){
			 if(this.columns.length > 13){
					return { x: this.columns.length*150-390 }
				}
			}
    },

     created() {
        this.initProcessTwoListBefore();
        this.initStandardUnitList();
        this.initProductList({});
        this.initWorkStationList();
        this.initErrorLevelList();
        this.initTemplateTypeList();
         this.initProjectTypeList();
         this.initFirstProjectClassifyList();
         this.initSecondProjectClassifyList();
         this.initThirdProjectClassifyList();
        this.initTemplateCode();
          this.initButtonList();
          this.initColumns();
          this.setdefColumns();
         this.initTemplateUnitList();
          this.initInspectMethodList();
          this.initErrLevelList();
     },


    methods: {

        productSearch(value){
            this.initProductList({mcode:value+''});
        },

        productChange(value){
            this.pdForm.mcode ='';
            this.pdForm.mname ='';
            this.pdForm.mid = value;
            if(this.productMap[value]){
                this.pdForm.mcode = this.productMap[value].mcode;
                this.pdForm.mname = this.productMap[value].mname;
            }
        },
        dayjs,
        openAllInfo(record){
            this.activeKey = ['1'];
            let id = record.id;
            getAction('/mes-quality/mesQcInspectTemplateMaintain/selectById/'+id).then(res=>{
                if(res.success){
                    this.detailVisible=true;
                    if(res.data){
                        this.de = res.data;
                        this.getApprovalList(res.data.processId);
                    }

                }else{
                    this.$message.warning(res.msg);
                }
            })
        },
        initErrLevelList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_err_level'}).then(res=>{
                if(res.success){
                    this.errLevelList = res.data;
                    this.errLevelMap = this.listToMap(this.errLevelList,'value');
                }
            })
        },
        getApprovalList(processInstanceId){
            getAction('/poros-bpmengine/task/getTaskRecordList?processInstanceId='+processInstanceId).then(res=>{
                if(res.success){
                    this.de.approvalList = res.data;
                    let key  = 1;
                    this.de.approvalList.forEach(item=>{
                        item.key = key;
                        key = key +1;
                    })
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },

        initProjectTypeList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'project_type'}).then(res=>{
                if(res.success){
                    this.projectTypeList = res.data;
                    this.projectTypeMap = this.listToMap(this.projectTypeList,'value');
                }
            })
        },

        closeDetailBtn(){
            this.detailVisible=false;
        },

        initStandardUnitList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_details_tamplate_unit'}).then(res=>{
                if(res.success){
                    this.standardUnitList = res.data;
                    this.standardUnitMap = this.listToMap(this.standardUnitList,'value');
                }
            })
        },

        projectClassifyIdChange(){
            this.initCheckProjectList();
        },

        projectTypeIdChange(){

            if(!this.cpSearchParam.projectTypeId||this.cpSearchParam.projectTypeId==''){
                this.cpSearchParam.projectClassifyId = '';
                this.cpSearchParam.projectClassify = '';
                this.cpSearchParam.projectTypeId = "";
                this.cpSearchParam.projectType="";
                this.projectClassifyList = [];
                this.projectClassifyMap = [];
            }else{
                this.cpSearchParam.projectClassifyId = '';
                this.cpSearchParam.projectClassify = '';

                let projectTypeId = this.cpSearchParam.projectTypeId;
                if(this.projectTypeMap[projectTypeId]){
                    this.cpSearchParam.projectType = this.projectTypeMap[projectTypeId].title;
                }

                switch(projectTypeId){
                    case 1:
                        this.changeFirstProjectClassifyList();
                        break;
                    case 2:
                        this.changeSecondProjectClassifyList();
                        break;
                    case 3:
                        this.changeThirdProjectClassifyList();
                        break;
                    case 4:
                        let oldList = this.projectTypeList;
                        let resultList = [];
                        oldList.forEach(item=>{
                            if(item.value!=projectTypeId){
                                resultList.push(item);
                            }
                        })
                        this.projectClassifyList = resultList;
                        this.projectClassifyMap = this.listToMap(this.projectClassifyList,'value');
                        break;
                }
            }

            this.initCheckProjectList();

        },

        changeFirstProjectClassifyList(){
            this.projectClassifyList = this.projectClassifyList1;
            this.projectClassifyMap = this.projectClassifyMap1;
        },

        changeSecondProjectClassifyList(){
            this.projectClassifyList = this.projectClassifyList2;
            this.projectClassifyMap = this.projectClassifyMap2;
        },

        changeThirdProjectClassifyList(){
            this.projectClassifyList = this.projectClassifyList3;
            this.projectClassifyMap = this.projectClassifyMap3;
        },

        initFirstProjectClassifyList(){
            getAction('/basic-business/auto/baCptype/childList',{mtypelevel:3}).then(res=>{
                if(res.success){
                    this.projectClassifyList1 = res.data;
                    this.projectClassifyMap1 = this.listToMap(this.projectClassifyList1,'id');
                }
            })
        },

        initSecondProjectClassifyList(){
            getAction('/mes-quality/mesQcInspectTemplateMaintain/selectByProjectTypeId').then(res=>{
                if(res.success){
                    this.projectClassifyList2 = res.data;
                    this.projectClassifyMap2 = this.listToMap(this.projectClassifyList2,'projectClassifyId');
                }
            })
        },

        initThirdProjectClassifyList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'inspect_type'}).then(res=>{
                if(res.success){
                    this.projectClassifyList3 = res.data;
                    this.projectClassifyMap3 = this.listToMap(this.projectClassifyList3,'value');
                }
            })
        },

        productChange2(record){

            return {
                on: {
                    click: () => {
                        let value = record.id;

                        this.templateForm.mcode ='';
                        this.templateForm.mname ='';
                        this.templateForm.mid = value;
                        if(this.productMap[value]){
                            this.templateForm.mcode = this.productMap[value].mcode;
                            this.templateForm.mname = this.productMap[value].mname;
                        }
                    },
                },
            };



        },

        closeProductModal(){
            this.pdSmallModalVisible = false;
        },

        initProductList(data){
            getAction('/basic-business/auto/baCpinfoMain/queryLimit',data).then(res=>{
                if(res.success){
                    this.productList = res.data;
                    this.productMap = this.listToMap(this.productList,'id');
                }
            })
        },
        initCheckProjectList(){
            let data= {
                templateId:this.currentBasicId,
                projectNc:this.cpSearchParam.checkProjectSearch?this.cpSearchParam.checkProjectSearch:'',
                projectClassifyId:this.cpSearchParam.projectClassifyId?this.cpSearchParam.projectClassifyId.split('-')[0]:'',
                projectTypeId:this.cpSearchParam.projectTypeId?this.cpSearchParam.projectTypeId:'',
            }
            this.checkProjectSelectRowKeys = [];
            this.checkProjectSelectRows = [];
            getAction('/mes-quality/mesQcInspectTemplateMaintain/selectAllByConditions',data).then(res=>{
                if(res.success){
                    this.checkProjectTableData = res.data;
                    let key = 1;
                    this.checkProjectTableData.forEach(item=>{
                        item.key = key;
                        key = key+1;
                        item.templateId = this.currentBasicId;
                    })
                }else{

                }
            })
        },

        initWorkStationList(code){
          getAction('/mes-craft/craft/mesPeDefinition/getAllStationByTwoCode?processTwoCode='+code).then(res=>{
              if(res.success){
                  this.workStationList = res.data;
                  this.workStationMap = this.listToMap(this.workStationList,'id');
              }
          })
        },

        fileChange(){
            console.log(this.pdForm.fileUrl)

        },
        initTemplateUnitList(){

            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_details_tamplate_unit'}).then(res=>{
                if(res.success){
                    this.templateUnitList = res.data;
                    this.templateUnitMap = this.listToMap(this.templateUnitList,'value');
                }
            })
        },
        initErrorLevelList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_err_level'}).then(res=>{
                if(res.success){
                    this.errorLevelList = res.data;
                    this.errorLevelMap = this.listToMap(this.errorLevelList,'value');
                }
            })
        },

        deleteSelectTemplate(){
          let ids = "";
          this.templateSelectRows.forEach(item=>{
              ids = ids+ item.id+',';
          })
            ids = ids.substring(0,ids.length-1)
            console.log(ids)
            deleteAction('/mes-quality/mesQcInspectTemplateMaintain/deleteBatchMesQcDetailTemplateMaintain',{ids:ids}).then(res=>{
                if(res.success){
                    this.$message.success("删除成功!");
                    this.getTemplateDataList(this.currentBasicId);
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },

        openAddPdBtn(){
            this.pdSmallModalTitle = '产品/物料明细新增';
            this.pdSmallModalVisible = true;
            this.pdCurrentState = 1;
        },


        detailTemplateBtn(record){
            let id = record.id;
            let code = record.processTwoCode;
            let type = record.templateType;
            this.currentBasicId = id;
            if(type!=1&&type!=2){
                this.templateColType = 2
            }else{
                this.templateColType = 1
            }
            this.templateModalVisible = true;
            this.templateTitle = '详细模板维护';

            this.templateForm.mid='';
            this.templateForm.mcode='';
            this.templateForm.mname='';

            if(this.templateTypeMap[type]){
                this.templateTitle = this.templateTitle + "(" + this.templateTypeMap[type].title +")";
            }

            this.getTemplateDataList(id);
            this.initWorkStationList(code);
        },

        openPhotoBtn(text){
            let obj = JSON.parse(text);
            if(obj&&obj.length>0){
                let filePath = obj[0].filePath;
                filePath = filePath.substring(filePath.indexOf('=')+1)
                this.photoUrl = filePath;
            }
            this.photoVisible=true;
        },


        getTemplateDataList(id){



            this.templateSelectRowKeys =[];
            this.templateSelectRows = [];


            getAction('/mes-quality/mesQcInspectTemplateMaintain/listMesQcDetailTemplateMaintainByMainId/'+id).then(res=>{
                if(res.success){
                    this.sortFlag = false;


                    this.templateTableData = res.data;
                    let key = 1;
                    let sort = 1;
                    this.templateTableData.forEach(item=>{
                        item.key = key;
                        key=key+1;
                        if(item.workstationId){
                            item.workstationId = item.workstationId+'-'+item.workstationname;
                        }

                        item.sort = sort;
                        if(item.valueType==2){
                            if(!item.standardValue||item.standardValue==''){
                                item.standardValue = 'PASS';
                            }
                        }

                        sort = sort + 1;
                    })
                }else{
                    this.message.warning(res.msg)
                }
            })
        },


        openTemplateAddBtn(){
          this.checkProjectVisible = true;
          this.initCheckProjectList();
        },
        checkProjectSearchChange(){
            this.initCheckProjectList();
        },


        templateSaveBtn(){
          let data = this.templateTableData;

          let flag = true;
          let flag2 = true;

          data.forEach(item=>{
              if(item.valueType==1){
                  if((!item.upperValue||item.upperValue=='')&&(!item.downValue||item.downValue=='')&&(!item.standardValue||item.standardValue=='')){
                      flag = false;
                  }


              }else if(item.valueType==2){
                  if(!item.standardValue||item.standardValue==''){
                      flag2 = false;
                  }
              }
          })

            if(!flag){
                this.$message.error("[计量型]数据需完善'标准值'或'上下限'的值！");
            }
            if(!flag2){
                this.$message.error("[计数型]数据需完善'标准值'的值！");
            }

            if(flag&&flag2){
                data.forEach(item=>{

                    item.workstationId = item.workstationId?parseInt(item.workstationId.split('-')[0]):'';
                    item.workstationcode = this.workStationMap[item.workstationId]?this.workStationMap[item.workstationId].processmcode:'';
                    item.workstationname = this.workStationMap[item.workstationId]?this.workStationMap[item.workstationId].processmname:'';


                })

                postAction('/mes-quality/mesQcInspectTemplateMaintain/editDetailTemplate',data).then(res=>{
                    if(res.success){
                        if(!this.sortFlag){
                            this.templateModalVisible = false;
                        }
                        this.$message.success("保存成功！");
                        if(this.sortFlag){
                            this.getTemplateDataList(this.currentBasicId);
                        }



                    }else{
                        this.$message.warning(res.msg);
                        data.forEach(item=>{
                            item.workstationId = item.workstationId+'-'+item.workstationname;
                        })
                    }
                })
            }
        },



        //封装listToMap
        listToMap(list,name){
            let map = {};
            for(let i in list){
                map[list[i][name]] = list[i];
            }
            return map;
        },

        openProductModal(record){
            this.productModalVisible = true;
            let id = record.id;
            this.currentBasicId = id;
            this.queryProductDetailList();
        },


        queryProductDetailList(){
            let id = this.currentBasicId;
            let productSearchStr = this.productSearchStr;


            getAction('/mes-quality/mesQcInspectTemplateMaintain/selectByInspectTemplateId?id='+id+'&proNc='+productSearchStr).then(res=>{
                if(res.success){
                    this.productTableData = res.data;
                    let key = 1;
                    this.productTableData.forEach(item=>{
                        item.key = key;
                        key = key +1;
                    })
                    this.productSelectRows=[];
                    this.productSelectRowKeys=[];
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },

        openProductEditBtn(record){
            this.pdSmallModalVisible = true;
            this.pdSmallModalTitle = '产品/物料明细编辑';
            this.pdCurrentState = 2;
            this.productEditP = record;
            this.pdForm={
                mid:record.mid,
                mcode:record.mcode,
                mname:record.mname,
                fileUrl:record.fileUrl
            }


            console.log(this.pdForm)

            this.initProductList({mcode:record.mcode});
        },

        queryOtherData(){
            let templateId = this.currentBasicId;
            let mcode = this.templateForm.mcode;

            getAction('/mes-quality/mesQcInspectTemplateMaintain/selectTemplateDetailByMcode?templateId='+templateId+'&mcode='+mcode).then(res=>{
                if(res.success){
                    this.$message.success('操作成功！');
                    this.getTemplateDataList(templateId);
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },

        saveProductDetail(){
            let flag = true;

            if(this.pdForm.mid==''){
                flag = false;
                this.$message.warning("请选择产品/物料！");
            }

            if(flag){
                if(this.pdCurrentState==1){
                    this.productAddOperation();
                }else if(this.pdCurrentState==2){
                    this.productEditOperation();
                }
            }

        },

        productEditOperation(){
            let data = this.pdForm;
            let p = this.productEditP;
            p.mid = data.mid;
            p.mcode = data.mcode;
            p.mname = data.mname;
            p.fileUrl = data.fileUrl;

            putAction('/mes-quality/mesQcInspectTemplateMaintain/editProductDetail',p).then(res=>{
                if(res.success){
                    this.pdSmallModalVisible= false;
                    this.$message.success("修改成功");
                    this.queryProductDetailList();
                    this.pdForm.mid = '';
                    this.pdForm.mcode = '';
                    this.pdForm.mname = '';
                    this.pdForm.fileUrl = '';
                    this.initProductList({mcode:''});
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },

        productAddOperation(){
            let data = this.pdForm;
            data.mesItmId = this.currentBasicId;

            postAction('/mes-quality/mesQcInspectTemplateMaintain/addProductDetail',data).then(res=>{
                if(res.success){
                    this.pdSmallModalVisible= false;
                    this.$message.success("新增成功");
                    this.queryProductDetailList();
                    this.pdForm.mid = '';
                    this.pdForm.mcode = '';
                    this.pdForm.mname = '';
                    this.pdForm.fileUrl = '';
                    this.initProductList({mcode:''});
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },



        pModalOk(){
            let flag = true;

            if(this.form.templateType==1||this.form.templateType==2){
                if(!this.form.processTwoId||this.form.processTwoId==''){
                    flag = false;
                    this.$message.error("请选择二级工序！");
                }
            }

            if(flag){
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        if(this.currentState==1){
                            this.pAddOperation();
                        }else if(this.currentState==2){
                            this.pEditOperation();
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        },

        pAddOperation(){

            let data = this.form;
            if(data.processTwoId){
                data.processTwoId=data.processTwoId.split('-')[0];
            }

            postAction('/mes-quality/mesQcInspectTemplateMaintain/add',data).then(res=>{
                if(res.success){
                    this.pModalVisible  = false;
                    this.$message.success('新增成功');
                    this.loadData();
                    this.initTemplateCode();
                }else{
                    this.$message.warning(res.msg);

                    if(this.form.processTwoId){
                        this.form.processTwoId=this.form.processTwoId+'-'+this.form.processTwoName
                    }
                }
            })
        },

        pEditOperation(){
            let data = this.form;
            let result = this.editP;
            result.templateCode=data.templateCode;
            result.templateName=data.templateName;
            result.templateType=data.templateType;
            result.processTwoId=data.processTwoId;
            result.processTwoCode=data.processTwoCode;
            result.processTwoName=data.processTwoName;
            result.isCustTemplate=data.isCustTemplate;
            result.remark=data.remark;

            if(result.processTwoId){
                result.processTwoId=result.processTwoId.split('-')[0];
            }




            putAction('/mes-quality/mesQcInspectTemplateMaintain/edit',result).then(res=>{
                if(res.success){
                    this.pModalVisible  = false;
                    this.$message.success('修改成功');
                    this.loadData();
                }else{
                    this.$message.warning(res.msg);
                    if(this.form.processTwoId){
                        this.form.processTwoId=this.form.processTwoId+'-'+this.form.processTwoName
                    }
                    this.loadData();
                }
            })

        },
        getMethodList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_inspect_method'}).then(res=>{
                if(res.success){
                    this.methodList = res.data;
                    this.methodMap = this.listToMap(this.methodList,'value');
                }
            })
        },
        initInspectMethodList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_inspect_method'}).then(res=>{
                if(res.success){
                    this.inspectMethodList = res.data;
                    this.inspectMethodMap = this.listToMap(this.inspectMethodList,'value');
                }
            })
        },

        initTemplateTypeList(){
            getAction('/basic-business/sys/dict/queryDictItemsByCode',{dictCode:'mes_template_type'}).then(res=>{
                if(res.success){
                    this.templateTypeList = res.data;
                    this.templateTypeMap = this.listToMap(this.templateTypeList,'value');
                }
            })
        },


        initProcessTwoListBefore(){
            getAction('/mes-craft/craft/mesPeDefinition/getAllSecondDef').then(res=>{
                if(res.success){
                    this.processTwoList = res.data;
                    this.processTwoMap = this.listToMap(this.processTwoList,'id');
                }
            })
        },

        initProcessTwoList(){



            let inspectType = this.form.templateType;

            if(!this.isGetEdit){
                this.form.processTwoId='';
                this.form.processTwoCode='';
                this.form.processTwoName='';
            }

            if(inspectType==5){
                this.form.isCustTemplate = 2;
            }else{
                this.form.isCustTemplate = '';
            }

        },

        processTwoSelectChange(){
          let processTwoId = this.form.processTwoId.split('-')[0];
            if(this.processTwoMap[processTwoId]){
                this.form.processTwoCode = this.processTwoMap[processTwoId].processmcode;
                this.form.processTwoName = this.processTwoMap[processTwoId].processmname;
            }
        },

        initTemplateCode(){
            getAction('/basic-business/sys/fillRule/getFillRule/',{ruleCode:'mes_inspect_template_rule'}).then(res=>{
                if(res.success){
                    this.templateCode = res.data;
                }
            })
        },

        selectPruductSmall(record) {
            return {
                on: {
                    click: () => {
                        this.pdForm.mid = record.id;
                        this.pdForm.mcode = record.mcode;
                        this.pdForm.mname = record.mname;
                    },
                },
            };
        },
        arrowUp(record){

            let key = record.key;
            this.templateTableData[key-1].sort  = this.templateTableData[key-1].sort - 1;
            this.templateTableData[key-1].key  = this.templateTableData[key-1].key - 1;
            this.templateTableData[key-2].sort  = this.templateTableData[key-2].sort + 1;
            this.templateTableData[key-2].key  = this.templateTableData[key-2].key + 1;

            this.changeIndexFinal();
        },
        arrowDown(record){

            let key = record.key;
            this.templateTableData[key-1].sort  = this.templateTableData[key-1].sort + 1;
            this.templateTableData[key-1].key  = this.templateTableData[key-1].key + 1;
            this.templateTableData[key].sort  = this.templateTableData[key].sort - 1;
            this.templateTableData[key].key  = this.templateTableData[key].key - 1;

            this.changeIndexFinal();
        },

        beforeChangeIndex(){
            this.templateSelectRowKeys =[];
            this.templateSelectRows = [];
        },
        changeIndexFinal(){
            this.beforeChangeIndex();
            let map = this.listToMap(this.templateTableData,'key');
            let list = [];

            for(let i=1;i<=this.templateTableData.length;i++){
                list.push(map[i]);
            }
            this.templateTableData  = list;
        },
        indexToFirst(record){
            let key = record.key;


            for(let i=key-2;i>=0;i--){
                this.templateTableData[i].sort  = this.templateTableData[i].sort + 1;
                this.templateTableData[i].key  = this.templateTableData[i].key + 1;
            }
            this.templateTableData[key-1].sort  = 1;
            this.templateTableData[key-1].key  = 1;
            this.changeIndexFinal();
        },

        indexToLast(record){
            let key = record.key;


            for(let i=key-1;i<this.templateTableData.length;i++){
                this.templateTableData[i].sort  = this.templateTableData[i].sort - 1;
                this.templateTableData[i].key  = this.templateTableData[i].key - 1;
            }
            this.templateTableData[key-1].sort  = this.templateTableData.length;
            this.templateTableData[key-1].key  = this.templateTableData.length;
            this.changeIndexFinal();
        },


        checkProjectAddBtn(){
            let data = this.checkProjectSelectRows;
            let result  = [];
            data.forEach(item=>{
                if(!item.inspectStandard||item.inspectStandard==''){
                    item.inspectStandard = 0;
                }
                result.push(
                    {
                        templateId:item.templateId,
                        inspectProjectId:item.id,
                        inspectProjectCode:item.inspectProjectCode,
                        inspectProject:item.inspectProjectName,
                        inspectStatand:item.inspectStandard,
                        valueType:item.inspectValueType,
                        inspectMethod:item.inspectMethod
                    }
                )
            })

            if(data.length==0){
                this.$message.error("请选择需要添加保存的检验项目");
            }else{
                postAction('/mes-quality/mesQcInspectTemplateMaintain/addDetailTemplate',result).then(res=>{
                    if(res.success){
                        this.checkProjectVisible = false;
                        this.$message.success("添加检验项目成功！");
                        this.getTemplateDataList(this.currentBasicId);
                    }else{
                        this.$message.warning(res.msg);
                    }
                })
            }

        },
        sendCheck(){

            if(this.selectedRowKeys.length==0){
                this.$message.warning('请勾选需要送审的数据！')
            }else{
                let result = '';
                this.selectedRowKeys.forEach(item=>{
                    result = result + item + ',';
                })
                result = result.substring(0,result.length-1);

                getAction('/mes-quality/mesQcInspectTemplateMaintain/send/approval?ids='+result).then(res=>{
                    if(res.success){
                        this.$message.success('送审成功！');
                        this.loadData();
                    }else{
                        this.$message.warning(res.msg);
                    }
                })
            }
        },

        openAddBtn(){
            this.pModalVisible = true;
            this.pTitle = '新增';
            this.currentState=1;
            this.form.templateCode = this.templateCode;

            this.form={
                templateCode:this.templateCode,
                    templateName:'',
                    templateType:'',
                    processTwoId:'',
                    isCustTemplate:'',
            }
        },

        openEditBtn(record){
            this.pModalVisible = true;
            this.pTitle = '编辑';
            this.currentState=2;
            this.editP = record;
            console.log(record)
            this.form={
                templateCode:record.templateCode,
                templateName:record.templateName,
                templateType:record.templateType,
                processTwoId:record.processTwoId+'-'+record.processTwoName,
                processTwoCode:record.processTwoCode,
                processTwoName:record.processTwoName,
                isCustTemplate:record.isCustTemplate,
                remark:record.remark,
            }


            getAction('/poros-bpmengine/task/getTaskRecordList?processInstanceId='+record.processId).then(res=>{
                if(res.success){
                    this.approvalList = res.data;
                    let key  = 1;
                    if(this.approvalList[0]&&this.approvalList[0].taskId){
                        this.editP.taskId = this.approvalList[0].taskId;
                    }
                }else{
                    this.$message.warning(res.msg);
                }
            })


            this.isGetEdit = true;
            this.initProcessTwoList();
            this.isGetEdit = false;
        },



        deleteBtn(id){
            deleteAction('/mes-quality/mesQcInspectTemplateMaintain/delete/'+id).then(res=>{
                if(res.success){
                    this.$message.success("删除成功！");
                    this.loadData();
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },



        templateOnSelectChange(selectedRowKeys, selectionRows){
            this.templateSelectRowKeys = selectedRowKeys;
            this.templateSelectRows = selectionRows;
        },

        checkProjectOnSelectChange(selectedRowKeys, selectionRows){
            this.checkProjectSelectRowKeys = selectedRowKeys;
            this.checkProjectSelectRows = selectionRows;
        },

        productOnSelectChange(selectedRowKeys, selectionRows){
            this.productSelectRowKeys = selectedRowKeys;
            this.productSelectRows = selectionRows;
        },

        deleteProductRows(){
            let data = this.productSelectRows;
            let ids = "";
            data.forEach(item=>{
                ids = ids+ item.id+',';
            })
            ids = ids.substring(0,ids.length-1)
            console.log(ids)

            deleteAction('/mes-quality/mesQcInspectTemplateMaintain/deleteByIds', {ids:ids}).then(res=>{
                if(res.success){
                    this.$message.success("删除成功！");
                    this.productSelectRows=[];
                    this.productSelectRowKeys=[];
                    this.queryProductDetailList();
                }else{
                    this.$message.warning(res.msg);
                }
            })
        },

      //确定按钮
      handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        this.searchText = selectedKeys[0];
        this.searchedColumn = dataIndex;
      },
      //取消按钮
      handleReset(clearFilters) {
        clearFilters();
        this.searchText = '';
      },
      //确定时间
      handleSearchDate(selectedKeys, confirm, dataIndex){
        confirm();
        this.searchText = selectedKeys[0];
        this.searchedColumn = dataIndex;
        this.searchQuery()
      },
      // 清除时间
      handleResetDate(clearFilters,begin,end) {
        if(this.queryParam[begin] || this.queryParam[end]){
          this.queryParam[begin] = ''
          this.queryParam[end] = ''
          clearFilters();
          this.searchText = '';
          this.searchQuery()
        }else{
          clearFilters();
          this.searchText = '';
        }

      },
      getKey () {
        const dataItem = []
        setTimeout(() => {
          this.columns.forEach(item => {
            dataItem.push({ 'text': item.title, 'value': item.dataIndex })
          })
        }, 100)
        return dataItem
      },
      //
      getControl (dic) {
        const dataItem = []
        initDictOptions(dic).then((res) => {
          res.data.forEach(item => {
            dataItem.push({ 'text': item.text, 'value': item.value })
          })
        })
        return dataItem
      },

      setdefColumns(){
        if(this.columns.length > 13){
          let arrLength = this.columns.length-1
          this.columns.forEach((item,index)=>{
              if(index>4&&index<arrLength-2){
                  item["width"] = 130
              }

          })

          this.columns[arrLength]['fixed'] = 'right'
          this.columns[arrLength-1]['fixed'] = 'right'
          this.columns[0]['fixed'] = 'left'
          this.columns[1]['fixed'] = 'left'
          this.columns[2]['fixed'] = 'left'
          this.columns[3]['fixed'] = 'left'
        }
      },
      initColumns(){
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name+":colsettings";
        let colSettings= Vue.ls.get(key);
        if(colSettings==null||colSettings==undefined){
          let allSettingColumns = [];
          this.defColumns.forEach(function (item,i,array ) {
            allSettingColumns.push(item.dataIndex);
          })
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        }else{
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter(item => {
            if(item.key =='rowIndex'|| item.dataIndex=='action'){
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          })
          this.columns =  cols;
        }
      },
      //列设置更改事件
      onColSettingsChange (checkedValues) {
        var key = this.$route.name+":colsettings";
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter(item => {
          if(item.key =='rowIndex'|| item.dataIndex=='action'){
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns =  cols;
      },
        //高级查询方法
        handleSuperQuery(arg) {
            if(!arg){
                this.superQueryParams=''
                this.superQueryFlag = false
            }else{
                this.superQueryFlag = true
                this.superQueryParams=JSON.stringify(arg)
            }
            this.loadData()
        },
        // 获取查询条件
        getQueryParams() {
            let sqp = {}
            if(this.superQueryParams){
                sqp['superQueryParams']=encodeURI(this.superQueryParams)
            }
            var param = Object.assign(sqp, this.queryParam, this.isorter);
            param.field = this.getQueryField();
            param.pageNo = this.ipagination.current;
            param.limit = this.ipagination.pageSize;
            return filterObj(param);
        },
      initDictConfig(){
        initDictOptions('mes_template_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'templateType', res.data)
          }
        })
        initDictOptions('ba_yn').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'isCustTemplate', res.data)
          }
        })
        initDictOptions('mes_audit_status').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions,'status', res.data)
          }
        })
      },
        clickThenSelect(record) {
            return {
                on: {
                    click: () => {
                        if(record.id){
                            this.rowId = record.id;
                            //this.onSelectChange(record.id.split(","), [record]);
                        }

                    },
                },
            };
        },
        setRowClassName(record){
            return record.id === this.rowId ? 'clickRowStyl' : '';
        },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
        this.selectedMainId=''
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedMainId=selectedRowKeys[0]
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        this.onClearSelected()
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.data.records;
            this.ipagination.total = res.data.total;
          }
          if(res.code===510){
            this.$message.warning(res.msg)
          }

        }).then(res=>{
            this.loading = false;
        })
      },

      // 弹出窗组件
      showDemoModal() {
        this.$refs.modalCompon.modalShow();
      },
      // 点击btn获取数据
      btnGetData(tableName,title){
        getAction(`${this.url.getColumns}`,{
          tableName:tableName
        }).then(
          res=>{
            if(res.code == 0){
              this.queryInfo = res.data.columns
              this.title = title
              this.dictOptions = res.data.dictOptions
              this.showDemoModal()
            }else{
               this.$message.warning(res.msg);
            }
          }
        )
      },

      //筛选分组
      getGroupTag(arrList) {
        let arr = [];
        var map = {},
            dest = [];
        arrList.forEach((item, index) => {
          if (item.groupTag) {
            arr.push(item);
          }
        });
        for (var i = 0; i < arr.length; i++) {
          var ai = arr[i];
          if (!map[ai.groupTag]) {
            dest.push({
              groupTag: ai.groupTag,
              name: ai.groupName,
              data: [ai]
            });
            map[ai.groupTag] = ai;
          } else {
            for (var j = 0; j < dest.length; j++) {
              var dj = dest[j];
              if (dj.groupTag == ai.groupTag) {
                dj.data.push(ai);
                break;
              }
            }
          }
        }
        this.groupTag = dest
        console.log(dest);
      },
      showLinkButton(item,record){
          let btn = new ButtonExpHandler(item.exp,record);
          return btn.show;
      },
        initButtonList(){
          getAction(`${this.url.getColumns}851461ecc4bf4bd19ac2dbf543ce8025`).then((res)=>{
            console.log("--获取自定义按钮->>",res);
            if(res.success){
              this.code = res.data.code;
              this.initCgButtonList(res.data.cgButtonList);
              this.initCgEnhanceJs(res.data.enhanceJs);
              this.getGroupTag(res.data.cgButtonList);
            }else{
              this.$message.warning(res.msg)
            }
          })
        },
        initCgEnhanceJs(enhanceJs){
          //console.log("--onlineList-js增强",enhanceJs)
          if(enhanceJs){
            let Obj = eval ("(" + enhanceJs + ")");
            this.EnhanceJS = new Obj(getAction,postAction,deleteAction);
            this.cgButtonJsHandler('created')
          }else{
            this.EnhanceJS = ''
          }
        },
        initCgButtonList(btnList){
          let linkArr = []
          let buttonArr = []
          if(btnList && btnList.length>0){
            for(let i=0;i<btnList.length;i++){
              let temp = btnList[i]
              if(temp.buttonStyle=='button'){
                buttonArr.push(temp)
              }else if(temp.buttonStyle=='link'){
                linkArr.push(temp)
              }
            }
          }
          this.cgButtonLinkList = [...linkArr]
          this.cgButtonList=[...buttonArr]
          console.log("链接增强", this.cgButtonLinkList);
        },
        cgButtonJsHandler(buttonCode){
          if(this.EnhanceJS[buttonCode]){
            this.EnhanceJS[buttonCode](this)
          }
        },
        cgButtonActionHandler(buttonCode){
          //处理自定义button的 需要配置该button自定义sql
          if(!this.selectedRowKeys || this.selectedRowKeys.length==0){
            this.$message.warning("请先选中一条记录")
            return false
          }
          if(this.selectedRowKeys.length>1){
            this.$message.warning("请只选中一条记录")
            return false
          }
          let params = {
            formId:this.code,
            buttonCode:buttonCode,
            dataId:this.selectedRowKeys[0]
          }
          console.log("自定义按钮请求后台参数：",params)
          postAction(this.url.buttonAction,params).then(res=>{
            if(res.success){
              this.loadData()
              this.$message.success("处理完成!")
            }else{
              this.$message.warning("处理失败!")
            }
          })

        },
        cgButtonLinkHandler(record,buttonCode,optType){
          if(optType=="js"){
            if(this.EnhanceJS[buttonCode]){
              this.EnhanceJS[buttonCode](this,record)
            }
          }else if(optType=="action"){
            let params = {
              formId:this.code,
              buttonCode:buttonCode,
              dataId:record.id
            }
            console.log("自定义按钮link请求后台参数：",params)
            postAction(this.url.buttonAction,params).then(res=>{
              if(res.success){
                this.loadData()
                this.$message.success("处理完成!")
              }else{
                this.$message.warning("处理失败!")
              }
            })
          }
        },

    }
  }
</script>
<style scoped>
    @import "~@assets/less/common.less";
    .myImg{
        width: auto;
        height: auto;
        max-width: 100%;
        max-height: 100%;
    }
    /deep/.clickRowStyl td{
        background:#00b4ed !important;
    }

    /deep/.ant-table-tbody.clickRowStyl:hover>td {
        background-color:#00b4ed
    }
</style>

